

struct TreeNode {
  int val;
  TreeNode *left;
  TreeNode *right;
  TreeNode()
      : val(0), left(nullptr), right(nullptr){} * TreeNode(int x)
      : val(x),
        left(nullptr), right(nullptr) {}
  TreeNode(int x, TreeNode *left, TreeNode *right)
      : val(x), left(left), right(right) {}
};

void dfs(TreeNode *root, int &k, int &res) {
  if (k == 0) {
    return;
  }
  if (root->left != nullptr) {
    dfs(root->left, k, res);
  }
  k--;
  if (k == 0) {
    res = root->val;
    return;
  }
  if (root->right != nullptr) {
    dfs(root->right, k, res);
  }
}

int kthSmallest(TreeNode *root, int k) {
  int res = 0;
  dfs(root, k, res);
  return res;
}